const ArtilceArchives = require("../../models/article/archivesModule.js");
const getArticleArchives = async (_, res) => {
    const dateFormat = await ArtilceArchives.findAll({
      order: [
        ["year", "DESC"],
        ["month", "DESC"],
        ["createdAt", "DESC"],
      ], // 按年份、月份和创建时间降序排序
    });
    const articleArchiveData =  groupAndSortArticles(dateFormat)
    res.send({
      code: 200,
      data: articleArchiveData,
    })
  }
const groupAndSortArticles = (articles) => {
  // 文章分组函数
  const groupedArticles = articles.reduce((result, article) => {
    const year = article.year;
    const month = article.month;

    // 确保每个 year 和 month 都有对应的分组
    if (!result[year]) {
      result[year] = {};
    }
    if (!result[year][month]) {
      result[year][month] = [];
    }
    result[year][month].push(article);
    return result;
  }, {});
  // 对年份中的月份进行降序排序
  Object.keys(groupedArticles).forEach((year) => {
    const months = groupedArticles[year];
    const sortedMonths = Object.keys(months).sort((a, b) => parseInt(b) - parseInt(a)); // 转换为数字进行排序
    const sortedYear = {};

    sortedMonths.forEach((month) => {
      sortedYear[month] = months[month];
    });

    groupedArticles[year] = sortedYear;
  });
  return groupedArticles;
}

module.exports = getArticleArchives;
